const input  = document.querySelector('.input1');
const btn1   = document.querySelector('.btn1');
const ul1    = document.querySelector('.ul1');
const box3   = document.querySelector('.box3');
const box4   = document.querySelector('.box4');

const pAll   = document.querySelector('#all   p');
const pWork  = document.querySelector('#work  p');
const pStudy = document.querySelector('#study p');
const pLife  = document.querySelector('#life  p');

const forms  = document.querySelectorAll('.box3 div form');

//选项卡切换
ul1.addEventListener("click", function (e) {
    if(e.target.nodeName !== "LI"){
        return;
    }
    let id = e.target.id;

    for (let j = 0; j < ul1.children.length; j++) {
        ul1.children[j].className = "";
        box3.children[j].className = "";
    }

    e.target.className = "showLi";
    let index = parseInt(id) - 1;
    if (box3.children[index]) {
        box3.children[index].className = "showDiv";
    }
});

//数据添加函数
function addTask(id, categoryArray, text, completed) {
    let oldArr = JSON.parse(localStorage.getItem('tasks') || '[]');
    let newTask = {
        id : id,
        category : categoryArray[1],
        text : text,
        completed: completed
    };
    oldArr.unshift(newTask);
    localStorage.setItem('tasks', JSON.stringify(oldArr));
}

//数据添加点击事件
btn1.addEventListener('click', function () {
    let time = new Date();
    let id = time.getTime();
    let category = ['all', 'work'];
    let text = input.value.trim();
    let completed = false;
    let reg = /^(?!\d)[\u4e00-\u9fa5A-Za-z0-9_$@#()]{2,40}$/;
    if (!reg.test(text)) {
        alert("错误")
        return
    }
    addTask(id, category, text, completed);

    input.value = '';

    show()
    tasksNum()
});

// 渲染任务列表函数
function show() {
    let tasks = JSON.parse(localStorage.getItem('tasks') || '[]');
    for (let i = 0; i < forms.length; i++) {
        while (forms[i].nextElementSibling && forms[i].nextElementSibling.tagName === 'FORM') {
            forms[i].nextElementSibling.remove();
        }
    }

    for (let i = 0; i < tasks.length; i++) {
        let task = tasks[i];
        let text = task.text;
        let category = task.category;
        let id = task.id;
        let completed = task.completed;

        let form = forms[0].cloneNode(true);
        form.setAttribute('id', id);
        form.removeAttribute('class');
        form.style.display = 'flex';
        form.children[1].innerText = text;
        form.children[2].innerText = category;

        if (completed) {
            form.children[0].checked = true;
            form.children[1].classList.add('ptext2');
        }

        box3.children[0].appendChild(form);

        if (category === 'work') {
            let f1 = forms[1].cloneNode(true);
            f1.setAttribute('id', id);
            f1.removeAttribute('class');
            f1.style.display = 'flex';
            f1.children[1].innerText = text;
            f1.children[2].innerText = category;
            if (completed) {
                f1.children[0].checked = true;
                f1.children[1].classList.add('ptext2');
            }
            box3.children[1].appendChild(f1);
        } else if (category === 'study') {
            let f2 = forms[2].cloneNode(true);
            f2.setAttribute('id', id);
            f2.removeAttribute('class');
            f2.style.display = 'flex';
            f2.children[1].innerText = text;
            f2.children[2].innerText = category;
            if (completed) {
                f2.children[0].checked = true;
                f2.children[1].classList.add('ptext2');
            }
            box3.children[2].appendChild(f2);
        } else if (category === 'life') {
            let f3 = forms[3].cloneNode(true);
            f3.setAttribute('id', id);
            f3.removeAttribute('class');
            f3.style.display = 'flex';
            f3.children[1].innerText = text;
            f3.children[2].innerText = category;
            if (completed) {
                f3.children[0].checked = true;
                f3.children[1].classList.add('ptext2');
            }
            box3.children[3].appendChild(f3);
        }
    }

    if (tasks.length > 0) {
        pAll.setAttribute("class", "hide")
    } else {
        pAll.removeAttribute("class")
    };
 
    let hasWork = false;
    let hasStudy = false;
    let hasLife = false;

    for (let j = 0; j < tasks.length; j++) {
        let cat = tasks[j].category;
        if (cat === 'work') hasWork = true;
        if (cat === 'study') hasStudy = true;
        if (cat === 'life') hasLife = true;
    }
    if (pWork) {
        if (hasWork) {
            pWork.setAttribute("class", "hide");
            
        } else {
            pWork.removeAttribute("class");
        }
    }
    if (pStudy) {
        if (hasStudy) {
            pStudy.setAttribute("class", "hide");
        } else {
            pStudy.removeAttribute("class");
        }
    }
    if (pLife) {
        if (hasLife) {
            pLife.setAttribute("class", "hide");
        } else {
            pLife.removeAttribute("class");
        }
    }
}

show()

//删除
for (let i = 0; i < box3.children.length; i++) {
    box3.children[i].addEventListener("click", function (e) {
        if (e.target.classList.contains("del")) {
            let formNode = e.target.parentNode;
            let id = formNode.getAttribute("id");
            formNode.remove();
            let tasks = JSON.parse(localStorage.getItem("tasks") || "[]");
            let newTasks = [];
            for (let j = 0; j < tasks.length; j++) {
                if (tasks[j].id != id) {
                    newTasks.push(tasks[j]);
                }
            }
            localStorage.setItem("tasks", JSON.stringify(newTasks));
            tasksNum();
            show()
        }
    });
}

// 任务完成确认
function tasksOver() {
    for (let i = 0; i < box3.children.length; i++) {
        box3.children[i].addEventListener("click", function (e) {
            if (e.target.classList.contains("ch")) {
                let id = e.target.parentNode.getAttribute("id");
                let tasks = JSON.parse(localStorage.getItem("tasks") || "[]");
                let index = -1;
                for (let j = 0; j < tasks.length; j++) {
                    if (tasks[j].id == id) {
                        index = j;
                        break;
                    }
                }
                if (index !== -1) {
                    tasks[index].completed = e.target.checked;
                    localStorage.setItem("tasks", JSON.stringify(tasks));
                    for (let k = 0; k < box3.children.length; k++) {
                        let forms = box3.children[k].querySelectorAll("form");
                        for (let m = 0; m < forms.length; m++) {
                            let form = forms[m];
                            if (form.getAttribute("id") == id) {
                                let checkbox = form.children[0];
                                let text = form.children[1];
                                checkbox.checked = e.target.checked;
                                if (e.target.checked) {
                                    text.classList.add("ptext2");
                                } else {
                                    text.classList.remove("ptext2");
                                }
                            }
                        }
                    }
                    tasksNum();
                }
            }
        });
    }
}

tasksOver()


//数据统计
function tasksNum() {
    let tasks = JSON.parse(localStorage.getItem("tasks") || "[]");
    let total = tasks.length;
    let completed = 0;
    for (let i = 0; i < tasks.length; i++) {
        if (tasks[i].completed) {
            completed++;
        }
    }
    let percent = total === 0 ? 0 : parseInt((completed / total) * 100);
    box4.children[0].textContent = "总任务：" + total;
    box4.children[1].textContent = "已完成：" + completed + "（" + percent + "%）";
}

tasksNum()

//修改内容与标签
for (let i = 0; i < box3.children.length; i++) {
    box3.children[i].addEventListener("click", function (e) {
        if (e.target.classList.contains("xg")) {
            let formNode = e.target.parentNode;
            let textP = formNode.children[1];
            let tagP = formNode.children[2];
            let xg = formNode.children[3];
            let del = formNode.children[4];
            let oldText = textP.innerText;
            let oldTag = tagP.innerText;

            const editDiv   = document.createElement('div');
            editDiv.className = 'editDiv'; 

            const inputEdit = document.createElement('input');
            inputEdit.type  = 'text';
            inputEdit.value = oldText;

            const selectEdit = document.createElement('select');
            ['work','study','life'].forEach(tag=>{
            const opt = document.createElement('option');
            opt.value = opt.textContent = tag;
            if(tag===oldTag) opt.selected = true;
            selectEdit.appendChild(opt);
            });

            const confirmBtn = document.createElement('button');
            confirmBtn.innerText = '确认';
            confirmBtn.className = 'confirm';

            editDiv.append(inputEdit, selectEdit, confirmBtn);

            textP.style.display = "none";
            tagP.style.display = "none";
            xg.style.display = "none";
            del.style.display = "none";
            
            formNode.insertBefore(editDiv, e.target);
            editDiv.style.display = "flex";

            confirmBtn.addEventListener("click", function () {
                let newText = inputEdit.value.trim();
                let newTag = selectEdit.value;
                if (newText === "") {
                    alert("内容不能为空");
                    return;
                }

                let id = formNode.getAttribute("id");
                let tasks = JSON.parse(localStorage.getItem("tasks") || "[]");
                for (let idx = 0; idx < tasks.length; idx++) {
                    if (tasks[idx].id == id) {
                        tasks[idx].text = newText;
                        tasks[idx].category = newTag;
                        break;
                    }
                }
                localStorage.setItem("tasks", JSON.stringify(tasks));
                show();
                tasksNum();
            });
        }
    });
}




const life = document.querySelector(".life")
life.addEventListener("click", function() {
    tasks = JSON.parse(localStorage.getItem('tasks') || '[]')
    tasks.forEach(function(item) {
        item["category"] = "life"
    })
    localStorage.setItem("tasks", JSON.stringify(tasks))
    show()
    console.log(tasks)
})

// function completeTime() {
//     tasks = JSON.parse(localStorage.getItem('tasks') || '[]')
//     let newTasks = tasks.map(function(item) {
//         item["completeTime"] = "";
//         return item
//     })
//     console.log(newTasks)
// }

function completeTime() {
    tasks = JSON.parse(localStorage.getItem('tasks') || '[]')
    let newTasks = tasks.map(function(item) {
        return {...item, "completeTime":""}
    })
    console.log(newTasks)
}


function num() {
    tasks = JSON.parse(localStorage.getItem('tasks') || '[]')
    let newTasks = tasks.filter(function(item) {
        reg = /\d+/
        if (reg.test(item.text)) {
            console.log(item)
        }
    })
}

function Symbol() {
    tasks = JSON.parse(localStorage.getItem('tasks') || '[]')
    let newTasks = tasks.map(function(item) {
        let id = Object.keys(item)
        let Id = Symbol(id[0])
        console.log(typeof(Id))

    })
}
Symbol()